﻿using Microsoft.Extensions.DependencyInjection;
using Niaofei.Application.Contracts;
using Niaofei.Domain;
using Niaofei.Injcetion;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Niaofei.Application.Services
{
    [Injection(typeof(ISysRightsAppService))]
    internal class SysRightsAppService : NiaofeiAppService, ISysRightsAppService
    {
        private readonly ISysRightsRepository _sysRightsRepository;

        public SysRightsAppService(IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _sysRightsRepository = serviceProvider.GetRequiredService<ISysRightsRepository>();
        }

        public async Task UpdateSysRights(List<SysRightsUpdateDto> input)
        {
            var rights = (await _sysRightsRepository.GetQueryableAsync())
                .Where(m => input.Select(n => n.Id).Contains(m.Id))
                .ToList();

            foreach (var rightDto in input)
            {
                var right = rights.FirstOrDefault(m => m.Id == rightDto.Id);
                if (right != null)
                {
                    Mapper.Map(rightDto, right);
                }
            }

            await _sysRightsRepository.UpdateManyAsync(rights);
        }

        public async Task<ResultDto<List<SysRightsDto>>> GetCurrentUserRights(int? menuId)
        {
            var rights = (await _sysRightsRepository.GetQueryableAsync())
                .WhereIf(menuId.HasValue, m => m.MenuId == menuId)
                .WhereIf(CurrentUser != null, m => CurrentUser!.Roles.Contains(m.RoleId))
                .ToList();

            var data = Mapper.Map<List<SysRights>, List<SysRightsDto>>(rights);

            return new ResultDto<List<SysRightsDto>>(data);
        }

        public async Task<ResultDto<List<SysRightsDto>>> GetSysRights(SysRightsInputDto input)
        {
            var rights = (await _sysRightsRepository.GetQueryableAsync())
                .WhereIf(input.RoleId.HasValue, m => m.RoleId == input.RoleId)
                .WhereIf(input.MenuId.HasValue, m => m.MenuId == input.MenuId)
                .ToList();

            var data = Mapper.Map<List<SysRights>, List<SysRightsDto>>(rights);

            return new ResultDto<List<SysRightsDto>>(data);
        }

        public async Task AddSysRights(SysRightsAddDto input)
        {
            var right = Mapper.Map<SysRightsAddDto, SysRights>(input);

            await _sysRightsRepository.InsertAsync(right);
        }
    }
}
